//
//  KINGPhotoSelectorController.swift
//  照片选择
//
//  Created by king on 15/8/7.
//  Copyright © 2015年 king. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
private let kPhotoSelectMaxCount = 9


class KINGPhotoSelectorController: UICollectionViewController, KINGPhotoSelectorDelegate{
    //设置模型
    lazy var photos:[UIImage] = [UIImage]()
    //当前选中的item
    private var currentSelectItemIndex:Int?
    //因为不是collection的制定构造函数所以不用重写关键字
    init() {
        super.init(collectionViewLayout: UICollectionViewFlowLayout())
        view.backgroundColor = UIColor.orangeColor()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.registerClass(KINGPhotoSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        collectionView?.backgroundColor = UIColor.orangeColor()
        //获取布局方式 
        let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout
        flowLayout?.itemSize = CGSizeMake(80, 80)
        flowLayout?.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // MARK: UICollectionViewDataSource

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 修正只能添加固定个数的图片
        return photos.count < kPhotoSelectMaxCount ? photos.count + 1 : kPhotoSelectMaxCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! KINGPhotoSelectorCell
    
        cell.backgroundColor = UIColor.blueColor()
        cell.image = (indexPath.item < photos.count) ? photos[indexPath.item] : nil
        //设置代理
        cell.photoDelegate = self
    
        return cell
    }
    //MARK: - KINGPhotoSelectorDelegate
    private func selectPhotoBtnClick(cell: KINGPhotoSelectorCell) {
        print(__FUNCTION__)
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            print("不能打开相册")
            return
        }
        //保存住当前点击的图片
        let index = collectionView?.indexPathForCell(cell)
        currentSelectItemIndex = index!.item
        //创建控制器
        let photo = UIImagePickerController()
        //让控制器成为UIImagePickerController的代理
        photo.delegate = self
        //modal方式打开相册
        presentViewController(photo, animated: true, completion: nil)
    }
    private func removePhotoBtnClict(cell: KINGPhotoSelectorCell) {
        //根据cell获取选中的indexPath
        let indexPath = collectionView?.indexPathForCell(cell)
        //删除数组中的数据
        photos.removeAtIndex(indexPath!.item)
        //刷新数据
        collectionView?.reloadData()
        //print(__FUNCTION__)
    }
}
//MARK: - UIImagePickerController代理方法
extension KINGPhotoSelectorController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //获取缩放图片，减少内存占用
        let img = image.scaleImage(300)
        if currentSelectItemIndex < photos.count {
            photos[currentSelectItemIndex!] = img
        } else {
            photos.append(img)
        }
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
}
//定义代理，通过代理，将点击方法传递给控制器
private protocol KINGPhotoSelectorDelegate: NSObjectProtocol {
    func selectPhotoBtnClick(cell:KINGPhotoSelectorCell)
    func removePhotoBtnClict(cell:KINGPhotoSelectorCell)
}
//自定义cell
private class KINGPhotoSelectorCell: UICollectionViewCell {
    //定义模型属性
    var image:UIImage? {
        didSet{
            if image == nil {
                selectPhotoBtn.setImage("compose_pic_add")
            } else {
                selectPhotoBtn.setImage(image, forState: UIControlState.Normal)
            }
            //如果是删除按钮，则隐藏删除按钮
            removePhotoBtn.hidden = (image == nil)
        }
    }
    
    //定义代理属性
    weak var photoDelegate: KINGPhotoSelectorDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    //如果类被定义成私有类的时候，需要把点击事件添加@objc
    @objc func selectBtnClick() {
        photoDelegate?.selectPhotoBtnClick(self)
    }
    
    @objc func removeBtnClict() {
        photoDelegate?.removePhotoBtnClict(self)
    }
    private func setupUI() {
        addSubview(selectPhotoBtn)
        addSubview(removePhotoBtn)
        
        selectPhotoBtn.addTarget(self, action: "selectBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        removePhotoBtn.addTarget(self, action: "removeBtnClict", forControlEvents: UIControlEvents.TouchUpInside)
        
        selectPhotoBtn.translatesAutoresizingMaskIntoConstraints = false
        removePhotoBtn.translatesAutoresizingMaskIntoConstraints = false
        let dict = ["select":selectPhotoBtn, "remove":removePhotoBtn]
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[select]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[select]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[remove]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[remove]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        
        //设置图片填充方式,这个地方不能使用直接设置UIButton的contentMode
        selectPhotoBtn.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //懒加载
    private lazy var selectPhotoBtn:UIButton = UIButton(imageName: "compose_pic_add")
    private lazy var removePhotoBtn:UIButton = UIButton(imageName: "compose_photo_close")
}
